package com.longdaji.decoration.ui.main.cart;

import android.content.Intent;
import android.os.Parcelable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.longdaji.decoration.R;
import com.longdaji.decoration.base.BaseFragment;
import com.longdaji.decoration.bean.Account;
import com.longdaji.decoration.data.bean.CartBean;
import com.longdaji.decoration.data.bean.PayRequestBean;
import com.longdaji.decoration.ui.pay.PayActivity;
import com.longdaji.decoration.utils.StringUtil;
import com.longdaji.decoration.widget.CommonDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by longtao on 2018/1/14.
 */

public class CartFragment extends BaseFragment implements CartContract.View, SwipeRefreshLayout.OnRefreshListener {
    private static final String TAG = CartFragment.class.getSimpleName();
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.tv_right_text)
    TextView mRightTxt;
    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.recycler_view_cart)
    RecyclerView mRecyclerViewCart;
    @BindView(R.id.btn_wear_collect)
    Button mBtnWearCollect;
    @BindView(R.id.btn_account_delete)
    Button mBtnAccountDelete;
    @BindView(R.id.tv_all)
    TextView mTvAll;
    @BindView(R.id.tv_money)
    TextView mTvMoney;
    @BindView(R.id.cb_select_all)
    CheckBox mCbSelectAll;
    @BindView(R.id.tv_no_data)
    TextView mTvNoData;
    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout mSwipeRefresh;
    @BindView(R.id.cb_self)
    CheckBox mCbSelf;
    @BindView(R.id.llyt_discount)
    LinearLayout mLlytDiscount;
    @BindView(R.id.llyt_self_support)
    LinearLayout mLlytSelfSupport;
    @Inject
    CartPresenter mPresenter;
    private CartAdapter adapter;
    private CartAdapter.CartItemListener mItemListener = new CartAdapter.CartItemListener() {
        @Override
        public void onCartItemClick(CartBean.Cart cartItem) {

        }

        @Override
        public void onCartCheckChange(int selectSize) {
            if (selectSize == adapter.getItemCount()) {
                mCbSelectAll.setChecked(true);
                mCbSelf.setChecked(true);
            } else {
                mCbSelectAll.setChecked(false);
                mCbSelf.setChecked(false);
            }
            selectChangeShowBottom();
        }

        @Override
        public void onChangeSkuNum(int position, long num) {
            Map<String, String> options = new HashMap<>();
            options.put("cartGoodsRecordId", adapter.getItemByPosition(position).getCartGoodsRecordId() + "");
            options.put("userId", adapter.getItemByPosition(position).getUserId() + "");
            options.put("skuId", adapter.getItemByPosition(position).getSkuId() + "");
            options.put("goodsSkuNum", num + "");
            mPresenter.modifyCartItemNum(options, position, num);
        }
    };
    private CommonDialog selfDialog;

    private void selectChangeShowBottom() {
        if ("编辑".equals(mRightTxt.getText())) {
            int count = 0;
            double price = 0;
            for (CartBean.Cart cartItem : adapter.getSelectData()) {
                price += cartItem.getGoodsSkuPrice() * cartItem.getGoodsSkuNum();
                count++;
            }
            mBtnAccountDelete.setText("结算(" + count + ")");
            mBtnWearCollect.setText("预约试戴(" + count + ")");
            mTvMoney.setText("¥" + StringUtil.formatNumber(price));
        }
    }

    @Inject
    public CartFragment() {
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_cart;
    }


    @Override
    protected void initView() {
        mPresenter.setView(this);
        mTvTitle.setText("购物车");
        mRightTxt.setText("编辑");
        mIvBack.setVisibility(View.GONE);
//        mCbSelectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//                Log.d(TAG, "try to update is" + b);
//                if (b) {
//                    adapter.setSelectAll();
//                } else {
//                    adapter.setSelectAllCancel();
//                }
//            }
//        });
        mCbSelectAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean checked = ((CheckBox) view).isChecked();
                mCbSelf.setChecked(checked);
                if (checked) {
                    adapter.setSelectAll();
                } else {
                    adapter.setSelectAllCancel();
                }
                selectChangeShowBottom();


            }
        });
        mCbSelf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean checked = ((CheckBox) view).isChecked();
                mCbSelectAll.setChecked(checked);
                if (checked) {
                    adapter.setSelectAll();
                } else {
                    adapter.setSelectAllCancel();
                }
                selectChangeShowBottom();
            }
        });
        initSwipe();
        initReclerView();
    }

    private void initSwipe() {
        // 设置颜色属性的时候一定要注意是引用了资源文件还是直接设置16进制的颜色，因为都是int值容易搞混
        // 设置下拉进度的背景颜色，默认就是白色的
        mSwipeRefresh.setProgressBackgroundColorSchemeResource(android.R.color.white);
        // 设置下拉进度的主题颜色
        mSwipeRefresh.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary, R.color.colorPrimaryDark);
        // 下拉时触发SwipeRefreshLayout的下拉动画，动画完毕之后就会回调这个方法
        mSwipeRefresh.setOnRefreshListener(this);
    }

    @Override
    public void onDestroy() {
        mPresenter.detachView();
        super.onDestroy();
    }

    private void initReclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        mRecyclerViewCart.setLayoutManager(layoutManager);
        adapter = new CartAdapter(getActivity(), new ArrayList<CartBean.Cart>(), mItemListener);
        mRecyclerViewCart.setAdapter(adapter);

    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
//        if (isVisible) {
//            mSwipeRefresh.setRefreshing(true);
//            mPresenter.getCartList(Account.getInstance().getUserid());
//        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mSwipeRefresh.setRefreshing(true);
        mPresenter.getCartList(Account.getInstance().getUserid());
    }

    @OnClick({R.id.tv_right_text, R.id.btn_wear_collect, R.id.btn_account_delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_right_text:
                adapter.setSelectAllCancel();
                mCbSelectAll.setChecked(false);
                mCbSelf.setChecked(false);
                mTvMoney.setText("¥0.0");
                if ("编辑".equals(mRightTxt.getText())) {
                    mRightTxt.setText("完成");
                    mBtnWearCollect.setVisibility(View.VISIBLE);
                    mBtnWearCollect.setText("移入收藏夹");
                    mBtnAccountDelete.setText("删除");
                    mTvAll.setVisibility(View.GONE);
                    mTvMoney.setVisibility(View.GONE);
                } else {
                    mRightTxt.setText("编辑");
                    mBtnWearCollect.setVisibility(View.GONE);
                    //mBtnWearCollect.setText("预约试戴");
                    mBtnAccountDelete.setText("结算");
                    mTvAll.setVisibility(View.VISIBLE);
                    mTvMoney.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.btn_wear_collect:
                if (adapter.getSelectData().size() == 0) {
                    toast("请选择商品");
                    return;
                }
                if ("编辑".equals(mRightTxt.getText())) {
//                    Intent intent = WearActivity.getStartIntent(getActivity());
//                    //intent.putParcelableArrayListExtra("cart_list", (ArrayList<? extends Parcelable>) adapter.getSelectData());
//                    int sum = 0;
//                    for (CartBean.Cart cartItem : adapter.getSelectData()) {
//                        long num = cartItem.getGoodsSkuNum();
//                        sum += num;
//                    }
//                    intent.putExtra("num", sum);
//                    intent.putExtra("image", "");
//                    startActivity(intent);
                } else {
                    mPresenter.collectChartGoods(Account.getInstance().getUserid(), adapter.getSelectData());
                }

                break;
            case R.id.btn_account_delete:
                if (adapter.getSelectData().size() == 0) {
                    toast("请选择商品");
                    return;
                }
                if ("编辑".equals(mRightTxt.getText())) {
                    Intent intent = PayActivity.getStartIntent(getActivity());
                    int sum = 0;
                    double price = 0;
                    List<PayRequestBean> list = new ArrayList<>();

                    for (CartBean.Cart cartItem : adapter.getSelectData()) {
                        long num = cartItem.getGoodsSkuNum();
                        sum += num;
                        price += cartItem.getGoodsSkuPrice() * num;
                        PayRequestBean payRequestBean = new PayRequestBean();
                        payRequestBean.setGoodsId(cartItem.getGoodsId());
                        payRequestBean.setCartId(cartItem.getCartGoodsRecordId());
                        payRequestBean.setGoodsName(cartItem.getGoodsName());
                        payRequestBean.setGoodsPrice(cartItem.getPrice());
                        payRequestBean.setProductNum((int) cartItem.getGoodsSkuNum());
                        payRequestBean.setSkuId(cartItem.getSkuId());
                        list.add(payRequestBean);
                    }
                    intent.putExtra("num", sum);
                    intent.putExtra("money", price);
                    intent.putExtra("image", adapter.getSelectData().get(0).getGoodsSkuImg());
                    intent.putParcelableArrayListExtra("good_list", (ArrayList<? extends Parcelable>) list);
                    startActivity(intent);
                } else {
                    selfDialog = new CommonDialog(getActivity());
                    selfDialog.setTitle("确定删除？");
                    selfDialog.setMessage("商品库存有限，请您慎重选择所要删除的商品");
                    selfDialog.setYesOnclickListener("确定", new CommonDialog.onYesOnclickListener() {
                        @Override
                        public void onYesClick() {
                            mPresenter.deleteChartGoods(Account.getInstance().getUserid(), adapter.getSelectData());
                            selfDialog.dismiss();
                        }
                    });
                    selfDialog.setNoOnclickListener("取消", new CommonDialog.onNoOnclickListener() {
                        @Override
                        public void onNoClick() {
                            selfDialog.dismiss();
                        }
                    });
                    selfDialog.show();

                }
                break;
            default:
                break;
        }
    }


    @Override
    public void showCartList(List<CartBean.Cart> list) {
        mSwipeRefresh.setRefreshing(false);
        if (list == null || list.size() <= 0) {
            mLlytDiscount.setVisibility(View.GONE);
            mLlytSelfSupport.setVisibility(View.GONE);
            mTvNoData.setVisibility(View.VISIBLE);
            mRecyclerViewCart.setVisibility(View.GONE);
        } else {
            mLlytDiscount.setVisibility(View.GONE);
            mLlytSelfSupport.setVisibility(View.VISIBLE);
            mTvNoData.setVisibility(View.GONE);
            mRecyclerViewCart.setVisibility(View.VISIBLE);
            adapter.setData(list);
        }
        resetState();


    }

    private void resetState() {
        adapter.setSelectAllCancel();
        mCbSelectAll.setChecked(false);
        mCbSelf.setChecked(false);
        if ("编辑".equals(mRightTxt.getText())) {
            mBtnAccountDelete.setText("结算(" + 0 + ")");
            mTvMoney.setText("¥" + 0.00);
        } else {

        }
    }

    @Override
    public void showDeleteCartSuccess(List<CartBean.Cart> cartList) {
        toast("删除成功！");
        //adapter.removeData(cartList);
        mSwipeRefresh.setRefreshing(true);
        mPresenter.getCartList(Account.getInstance().getUserid());
    }

    @Override
    public void showDeleteCartFail() {
        toast("删除失败！");
        resetState();
    }

    @Override
    public void changeCartItemNum(int position, long num) {
        adapter.getItemByPosition(position).setGoodsSkuNum(num);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void changeCartItemNumFail(String msg) {
        toast(msg);
    }

    @Override
    public void showCollectSuccess() {
        toast("收藏成功");
        resetState();
    }

    @Override
    public void showCollectFail() {
        toast("收藏失败");
        resetState();
    }

    @Override
    public void onRefresh() {
        mSwipeRefresh.setRefreshing(true);
        mPresenter.getCartList(Account.getInstance().getUserid());
    }
}
